package com.atguigu.juc.future;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Description: FutureTask 缺点
 * @author： yeswater
 * @create： 2024/5/28
 */

public class FutureApiDemo {
	public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
		//m1();
		m2();
	}
	
	/**
	 * isDone() 轮询会耗费CPU，也不能及时得到结果
	 */
	private static void m2() throws InterruptedException, ExecutionException {
		FutureTask<String> futureTask = new FutureTask<>(() -> {
			System.out.println(Thread.currentThread().getName() + " come in");
			try {
				TimeUnit.SECONDS.sleep(5);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			return Thread.currentThread().getName() + " over";
		});
		Thread t1 = new Thread(futureTask, "t1");
		t1.start();
		
		System.out.println(Thread.currentThread().getName() + " do other jobs");
		
		while (true) {
			if (futureTask.isDone()) {
				System.out.println(futureTask.get());
				break;
			} else {
				try {
					TimeUnit.MILLISECONDS.sleep(500);
					System.out.println("==== doing !!! ====");
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		}
		
	}
	
	/**
	 * future task get() 容易阻塞 
	 */
	private static void m1() throws InterruptedException, ExecutionException {
		FutureTask<String> futureTask = new FutureTask<>(() -> {
			System.out.println(Thread.currentThread().getName() + " come in");
			try {
				TimeUnit.SECONDS.sleep(5);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			return Thread.currentThread().getName() + " over";
		});
		Thread t1 = new Thread(futureTask, "t1");
		t1.start();
		
		System.out.println(futureTask.get()); // get() 容易阻塞
		//System.out.println(futureTask.get(3, TimeUnit.SECONDS));
		
		System.out.println(Thread.currentThread().getName() + " do other jobs");
	}
}
